
import java.awt.*;
import java.sql.SQLException;
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;

public class AjoutElement extends JDialog implements ActionListener {

  private JLabel lNom;
  private JLabel lCat;
  private JTextField tNom;
  private JComboBox cbCat;
  private JButton bOk;
  private JButton bQuit;
  private Container contenu;

  public AjoutElement() {
    super((JDialog) null, true);
    this.setLayout(null);
    this.setTitle("Ajout element");

    this.lNom = new JLabel("Nom: ");
    this.lCat = new JLabel("Categorie: ");
    this.tNom = new JTextField();

    String[] t = null;

    try {
      ArrayList<Categorie> categories = Categorie.chargerCategories();
      t = new String[categories.size()];
      int i = 0;
      for (Categorie categorie : categories) {
        t[i] = categorie.getNom();
        i++;
      }
    } catch (SQLException ex) {
      JOptionPane.showMessageDialog(this, ex.getMessage(), "Erreur", JOptionPane.ERROR_MESSAGE);
    }

    this.cbCat = new JComboBox();
    this.cbCat = new JComboBox(t);
    this.cbCat.setMaximumRowCount(2);

    this.bOk = new JButton("Créer");
    this.bOk.addActionListener(this);

    this.bQuit = new JButton("Annuler");
    this.bQuit.addActionListener(this);

    this.contenu = this.getContentPane();

    this.contenu.add(this.lNom);
    this.contenu.add(this.lCat);
    this.contenu.add(this.tNom);
    this.contenu.add(this.cbCat);
    this.contenu.add(this.bOk);
    this.contenu.add(this.bQuit);

    this.lNom.setBounds(10, 10, 100, 20);
    this.tNom.setBounds(130, 10, 100, 20);
    this.lCat.setBounds(10, 40, 100, 20);
    this.cbCat.setBounds(130, 40, 100, 20);
    this.bOk.setBounds(10, 70, 100, 20);
    this.bQuit.setBounds(130, 70, 100, 20);

    this.setBounds(20, 20, 300, 200);
    this.setVisible(true);
    this.setResizable(false);
  }

  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == bOk) {
      Object obj = cbCat.getSelectedItem();
      String catStr = (String) obj;
      Categorie cat;
      try {
        cat = Categorie.getCategorieNom(catStr);
        if (tNom.getText().equals("")) {
          JOptionPane.showMessageDialog(this, "L'item  n'a pas de nom", "Erreur", JOptionPane.ERROR_MESSAGE);
        } else {
          if (Item.exist(tNom.getText(), cat)) {
            JOptionPane.showMessageDialog(this, "L'item existe déjà", "Erreur", JOptionPane.ERROR_MESSAGE);
          } else {
            Item i1 = new Item(tNom.getText(), cat);
            JOptionPane.showMessageDialog(this, "L'item à été ajouté", "Ajout réussit", JOptionPane.INFORMATION_MESSAGE);
            this.dispose();
          }
        }

      } catch (SQLException ex) {
        JOptionPane.showMessageDialog(this, ex.getMessage(), "Erreur", JOptionPane.ERROR_MESSAGE);
      }
    }

    if (e.getSource() == bQuit) {
      this.dispose();
    }
  }
}
